﻿USE [ParieurProDB]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Franck Allion
-- Create date: 26/02/11
-- Description:	Delete an existing user
-- =============================================
CREATE PROCEDURE [dbo].[mybet_deleteuser]
	-- Add the parameters for the stored procedure here
	@UserId             uniqueidentifier,
	@UserName	nvarchar(256)
AS
BEGIN

	DECLARE @TranStarted   bit
    SET @TranStarted = 0
    
    DECLARE @ErrorCode   int
    SET @ErrorCode = 0
    
	IF( @@TRANCOUNT = 0 )
		BEGIN
		    BEGIN TRANSACTION
			SET @TranStarted = 1
		END
    ELSE
		BEGIN
			SET @ErrorCode = -1
    		GOTO Cleanup
		END

	-- Delete Ranks
    DELETE FROM [dbo].Ranks WHERE SubscriptionId=(
		SELECT SubscriptionId FROM [dbo].Subscriptions
		WHERE UserId=@UserId);
	
	IF( @@ERROR <> 0 )
    BEGIN
		SET @ErrorCode = -1
		GOTO Cleanup
    END

	-- Delete Subscriptions
	DELETE FROM [dbo].Subscriptions WHERE UserId=@UserId;
	IF( @@ERROR <> 0 )
    BEGIN
		SET @ErrorCode = -2
		GOTO Cleanup
    END	
	
	-- Delete Bets
	DELETE [dbo].UserBets WHERE UserId=@UserId
	IF( @@ERROR <> 0 )
    BEGIN
		SET @ErrorCode = -3
		GOTO Cleanup
    END	
    
    -- Delete EventScores
	DELETE [dbo].EventScores WHERE UserId=@UserId
	IF( @@ERROR <> 0 )
    BEGIN
		SET @ErrorCode = -10
		GOTO Cleanup
    END	
     
    -- Delete Membership   
    DELETE [dbo].aspnet_Membership 
		WHERE UserId=@UserId
	IF( @@ERROR <> 0 )
    BEGIN
		SET @ErrorCode = -8
		GOTO Cleanup
    END
    
    -- Delete User parameters    
 	DELETE [dbo].aspnet_Profile 
		WHERE UserId=@UserId
	IF( @@ERROR <> 0 )
    BEGIN
		SET @ErrorCode = -5
		GOTO Cleanup
    END
    
        -- Delete User parameters    
 	DELETE [dbo].aspnet_Profile 
		WHERE PropertyValuesString like @UserName
	IF( @@ERROR <> 0 )
    BEGIN
		SET @ErrorCode = -5
		GOTO Cleanup
    END
    
    	-- Delete User roles    
	DELETE [dbo].aspnet_UsersInRoles 
		WHERE UserId=@UserId
	IF( @@ERROR <> 0 )
    BEGIN
		SET @ErrorCode = -4
		GOTO Cleanup
    END
    

    
        -- Delete User  
   	DELETE [dbo].aspnet_Users 
		WHERE UserId=@UserId
	IF( @@ERROR <> 0 )
    BEGIN
		SET @ErrorCode = -6
		GOTO Cleanup
    END  

    -- Delete User  
   	DELETE [dbo].aspnet_Users 
		WHERE UserName=@UserName
	IF( @@ERROR <> 0 )
    BEGIN
		SET @ErrorCode = -7
		GOTO Cleanup
    END  
    
    -- commit transaction
    IF( @TranStarted = 1 )
    BEGIN
	    SET @TranStarted = 0
	    COMMIT TRANSACTION
    END
    
    SET @ErrorCode = 0
    
    SET ROWCOUNT 1
    
    RETURN 0
    
Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END
    
    SET ROWCOUNT 0
    
	RETURN @ErrorCode          	  
		
END
GO
